package com.marcjmcd.cop4331;

import java.util.LinkedList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Shortest extends Activity
{
	
	protected void onCreate(Bundle savedInstanceState)
	{
		//Code execution begins here
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shortest);
		
		//Buttons and their click listeners
		
		/*
		 * Back -
		 * 
		 */
		Button back = (Button) findViewById(R.id.button6);
		
		back.setOnClickListener(new OnClickListener() {
			
		@Override
		public void onClick(View v) 
		{
			Context context = getApplicationContext();
			
			//Return to the main activity
			startActivity(new Intent(context, Main.class));				
		}
		});
		
		/*
		 * Calculate -
		 * 
		 */
		Button calc = (Button) findViewById(R.id.button11);
		
		calc.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				
				
				Result res = new Result();
				res.execute();
				
				//CURRENTLY NEED: a way to check the status of the async task
				//while(res.getStatus() == android.os.AsyncTask.Status.PENDING || res.getStatus() == android.os.AsyncTask.Status.RUNNING)
					//System.out.println("Please Wait...");	
			}
		});
	}
	
	private class Result extends AsyncTask<Void, Void, LinkedList<String>>
	{
		protected LinkedList<String> doInBackground(Void...params) 
		{
			LinkedList<String> directions = new LinkedList<String>();
			
			EditText orig = (EditText) findViewById(R.id.shortest_editText1);
			EditText dest = (EditText) findViewById(R.id.shortest_editText2);
			
			System.out.println("Grabbed text fields");
			String origin = orig.getText().toString();
			String destination = dest.getText().toString();
			
			try
			{
				System.out.println("Entered try block");
				Directions dir = new Directions(origin, destination);
				directions = dir.calculate();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
			
			System.out.println("Returning...");
			return directions;
		}
		
		protected void onPostExecute(LinkedList<String> out)
		{
			Intent intent = new Intent(Shortest.this, shortestList.class);
			
			String[] data = new String[out.size()];
			
			//Converts to array
			for (int i = 0; i < data.length; i++) 
			{
				data[i] = out.get(i);
				System.out.println("Data[" + i + "] : "+ data[i++] + " (before sending)");
			}
			
			intent.putExtra("values", data);
			
			//Can't start activity!
			startActivity(intent);
		}
	}
}
